
import { ElMessageBox } from "element-plus"
import { useEditorStore } from "@/stores/editStore"
import { currentNodeInfo } from "@/stores/currentNodeStore"
import { storeToRefs } from "pinia"
import { useUserStore } from "@/stores/userStore"
import { CommentPluginKey } from "@/tiptap/extensions/CommentPlugin"
import { useCommentStore } from "@/stores/commentStore"
export const addComment = async () => {
 

  const {editorInstance} = storeToRefs(useEditorStore())

  const { state, view } = editorInstance.value
  const { from, to } = state.selection
  if (from === to) {
    ElMessageBox.alert('请先选中一段文字后再添加批注', '提示')
    return
  }

  const noteId = currentNodeInfo().nodeId
  const userId = useUserStore().user.id
  const commentId = `${noteId}_${userId}_${from}_${to}`

  const decoSet = CommentPluginKey.getState(state)
  const hasOverlap = decoSet.find(from, to).some(d => {
    const data = d.spec?.commentData
    if (!data) return false
    return !(data.to <= from || data.from >= to)
  })

  if (hasOverlap) {
    ElMessageBox.alert('该范围与已有批注重叠，请选择不同范围', '提示')
    return
  }

  const result = await ElMessageBox.prompt('请输入批注内容', '添加批注', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputPattern: /.+/,
    inputErrorMessage: '不能为空'
  })

  const anchorText = state.doc.textBetween(from, to)

  const commentData = {
    id: commentId,
    noteId,
    userId,
    from,
    to,
    comment: result.value,
    anchorText,
    broken: false
  }

  //在一个 setMeta 中同时传 add/remove（如果需要 remove，确保不会覆盖）
  const tr = state.tr.setMeta(CommentPluginKey, { add: commentData })
  view.dispatch(tr)
  const commentStore = useCommentStore()
commentStore.addComment(commentData)
}
